<?php
class Article extends CActiveRecord{
	
	public static function model($className = __CLASS__){
		return parent::model($className);
	}
	
	public function tableName(){
		return '{{article}}';
	}

	public function attributeLabels(){
		return array(
			'title'=>'文章标题',
			'category_id'=>'内容分类',
				'pic'=>'缩略图',
				'keywords'=>'关键字',
				'description'=>'描述',
				'content'=>'内容',
				'source'=>'来源',
				'writer'=>'作者'
			);
	}
	
	/**
	 * 验证规则
	 * @see CModel::rules()
	 */
	public function rules(){
		return array(
				array('user_id', 'numerical', 'message'=>'用户信息错误'),
				array('category_id', 'numerical', 'message'=>'请选择栏目'),
				array('title', 'required', 'message'=>'文章标题不能为空'),
				array('keywords,description','filter', 'filter'=>'strip_tags'),
				array('pic,writer,source', 'safe'),
				array('content', 'required', 'message'=>'内容不能为空'),
		);
	}

/**
 * 更新文章与关联模型的对应关系
 * @return [type] [description]
 */
	public function addAttr($articleId, $attrId){

		if(empty($articleId) || empty($attrId) || !is_array($attrId)){
			return false;
		}

		//首先删除该文章对应的属性
		Yii::app()->db->createCommand()->delete('{{article_attr}}', 'article_id = :article_id', array(':article_id'=>$articleId));

		$sql = 'INSERT INTO {{article_attr}}(article_id, attr_id) values (:article_id,:attr_id)';

		$db = Yii::app()->db->createCommand($sql);
		foreach($attrId as $v){
			$db->bindParam(':article_id', $articleId);
			$db->bindParam(':attr_id', $v);
			$db->execute();
		}
		return true;
	}
	
	/**
	 * 获取对应文章ID的属性
	 * @param int $articleId 	文章ID号
	 */
	public function getArticleAttr($articleId){
		$sql = "SELECT attr_id from {{article_attr}} where article_id = $articleId";
		$attrIds = Yii::app()->db->createCommand($sql)->queryAll();
		//组合成一位数组返回
		$attr = array();
		foreach($attrIds as $v){
			array_push($attr, $v['attr_id']);
		}
		return $attr;
	}
	
	/**
	 * 获取指定属性的文章
	 * @param array attrIds 	属性数组 
	 * @param array $cids 		栏目ID数组
	 */
	public function getPicArticle($attrIds, $cids = array(), $limit = ''){
		!empty($attrIds) && $attrIds = implode(',', $attrIds);
		$where = "aa.attr_id IN ({$attrIds})";
		if(!empty($cids)){
			$cids = implode(',', $cids);
			$andWhere = "a.category_id IN ({$cids})";
		} else {
			$andWhere = '';
		}
		$result = Yii::app()->db->createCommand()
				->select('*')
				->from('{{article_attr}} aa')	
				->leftJoin('{{article}} a', 'aa.article_id = a.article_id')
				->where($where)
				->andWhere($andWhere)
				->limit($limit)
				->queryAll();
		return $result;
	}
}